<template>
  <!-- 应知卡管理 -->
  <div class="shouldknowcard">
    <basic-container>
      <avue-crud
        :option="option"
        :table-loading="loading"
        :data="data"
        :page.sync="page"
        :permission="permissionList"
        :before-open="beforeOpen"
        v-model="form"
        ref="crud"
        @row-update="rowUpdate"
        @row-save="rowSave"
        @row-del="rowDel"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
      >
        <!-- 左上方菜单 -->
        <template slot="menuLeft">
          <el-button
            type="danger"
            size="small"
            icon="el-icon-delete"
            plain
            v-if="permission.knowablecard_delete"
            @click="handleDelete">
            删 除
          </el-button>
          <el-button
            type="warning"
            size="small"
            plain
            icon="el-icon-download"
            @click="handleExport">
            批量导出
          </el-button>
        </template>

        <!-- 风险等级表格自定义 -->
        <template slot="fxdj" slot-scope="scope">
          <div>
            <div
              :class="{
                fxdj_a: fxdjObj[scope.row['fxdj']] === 'A',
                fxdj_b: fxdjObj[scope.row['fxdj']] === 'B',
                fxdj_c: fxdjObj[scope.row['fxdj']] === 'C',
                fxdj_d: fxdjObj[scope.row['fxdj']] === 'D'
              }"
            >
              {{ fxdjObj[scope.row["fxdj"]].toUpperCase() }}
            </div>
          </div>
        </template>

        <!-- 附件表格自定义 -->
        <template slot="fj" slot-scope="scope">
          <div class="enclosure_div">
            <a :href="downloadHead + scope.row['fj']">
              <i class="el-icon-download"></i>下载附件
            </a>
          </div>
        </template>

        <!-- 风险管控措施表单自定义 -->
        <template slot="fxgkcsForm">
          <div>
            <el-button
              type="primary"
              size="small"
              :disabled="dialogType === viewLabel"
              @click="addControlMeasure()">
              添 加
            </el-button>
            <el-button
              type="success"
              style="margin-left: 15px;"
              size="small"
              :disabled="dialogType === viewLabel"
              @click="handleSelectControlMeasure()">
              选 择
            </el-button>
          </div>
        </template>

        <!-- 风险管控措施内容表单自定义 -->
        <template slot="fxgkcsContentForm">
          <div class="fxgkcsContent_div">
            <avue-crud
              :option="measureOption"
              :data="measureData"
              ref="measureCrud"
            >
              <!-- 自定义操作列：删除按钮 -->
              <template slot="menu" slot-scope="scope">
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="small"
                  :disabled="dialogType === viewLabel"
                  @click="handleDeleteMeasure(scope.row, scope.index)">
                  删 除
                </el-button>
              </template>

              <!-- 管控类型表格自定义 -->
              <template slot="gklx" slot-scope="scope">
                <el-select
                  placeholder="请选择管控类型"
                  v-model="scope.row['gklx']"
                  clearable
                  size="small"
                >
                  <el-option
                    v-for="(item, index) in controlMeasures"
                    :key="index"
                    :label="item.dictValue"
                    :value="item.dictKey">
                  </el-option>
                </el-select>
              </template>

              <!-- 管控措施表格自定义 -->
              <template slot="gkcs" slot-scope="scope">
                <el-input
                  placeholder="请输入管控措施"
                  v-model="scope.row['gkcs']"
                  clearable
                  size="small">
                </el-input>
              </template>
            </avue-crud>
          </div>
        </template>

        <!-- 附件表单自定义 -->
        <template slot="fjForm">
          <div>
            <el-upload
              action="/api/fileManager/upload/file"
              :headers="SetHeaders"
              :file-list="fjFileList"
              :before-upload="beforeUploadFJ"
              :on-remove="handleRemoveFJ"
              :on-success="uploadFJSuccess"
            >
              <el-button size="small" type="primary">选择文件</el-button>
            </el-upload>
          </div>
        </template>
      </avue-crud>
    </basic-container>

    <!-- 弹窗：选择管控措施 -->
    <controlmeasuredialog
      :chooseMeasureDialog="chooseMeasureDialog"
      :filterYHJB="filterYHJB"
      @chooseControlMeasure="chooseControlMeasure"
      @cancelChooseControlMeasure="cancelChooseControlMeasure"
      @handleCloseChooseMeasure="handleCloseChooseMeasure"
    >
    </controlmeasuredialog>
  </div>
</template>

<script>
import {
  getList,
  getDetail,
  add,
  update,
  remove,
  getControlMeasureTypes
} from "@/api/saferisk/shouldknowcard";
import { mapGetters } from "vuex";
import { getToken } from "@/util/auth";
import controlmeasuredialog from "./components/controlmeasuredialog.vue";

const tenantId = JSON.parse(localStorage.getItem("saber-tenantId")).content;

export default {
  components: {
    controlmeasuredialog
  },
  data() {
    return {
      form: {},
      query: {},
      data: [],
      loading: true,
      selectionList: [],
      page: {
        pageSize: this.$pageSize,
        currentPage: 1,
        total: 0
      },
      option: {
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchSpan: 5,
        searchMenuSpan: 4,
        border: true,
        viewBtn: true,
        selection: true,
        refreshBtn: true,
        columnBtn: false,
        dialogClickModal: false,
        column: [
          {
            label: "应知卡编号",
            prop: "yzkbh",
            align: "center",
            search: true,
            rules: [
              {
                required: true,
                message: "请输入应知卡编号",
                trigger: "blur"
              }
            ]
          },
          {
            label: "岗位名称",
            prop: "gwmc",
            align: "center",
            search: true,
            type: "select",
            dicUrl: "/api/blade-system/post/select?tenantId=" + tenantId,
            props: {
              label: "postName",
              value: "id"
            },
            rules: [
              {
                required: true,
                message: "请选择岗位名称",
                trigger: "change"
              }
            ]
          },
          {
            label: "主要危险有害因素",
            prop: "zywxyhys",
            align: "center",
            type: "textarea",
            span: 24,
            maxlength: 150,
            rules: [
              {
                required: true,
                message: "请输入主要危险有害因素",
                trigger: "blur"
              }
            ]
          },
          {
            label: "易导致事故风险",
            prop: "ydzsgfx",
            align: "center",
            hide: true,
            type: "textarea",
            span: 24,
            maxlength: 150,
            rules: [
              {
                required: true,
                message: "请输入易导致事故风险",
                trigger: "blur"
              }
            ]
          },
          {
            label: "应急处置对策",
            prop: "yjczdc",
            align: "center",
            hide: true,
            type: "textarea",
            span: 24,
            maxlength: 150,
            rules: [
              {
                required: true,
                message: "请输入应急处置对策",
                trigger: "blur"
              }
            ]
          },
          {
            label: "风险等级",
            prop: "fxdj",
            align: "center",
            search: true,
            slot: true,
            type: "select",
            dicUrl: "/api/blade-system/dict-biz/dictionary?code=risk_level",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            rules: [
              {
                required: true,
                message: "请选择风险等级",
                trigger: "change"
              }
            ]
          },
          {
            label: "安全警示标志",
            prop: "aqjsbz",
            align: "center",
            hide: true,
            type: "select",
            dicUrl:
              "/api/blade-system/dict-biz/dictionary?code=safe_warning_logo",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            rules: [
              {
                required: true,
                message: "请选择安全警示标志",
                trigger: "change"
              }
            ]
          },
          {
            label: "风险管控措施",
            prop: "fxgkcs",
            align: "center",
            span: 24,
            hide: true,
            formslot: true,
            rules: [
              {
                required: true,
                message: "请选择或添加风险管控措施",
                trigger: "blur"
              }
            ]
          },
          {
            label: "",
            prop: "fxgkcsContent",
            align: "center",
            span: 24,
            hide: true,
            formslot: true
          },
          {
            label: "附件",
            prop: "fj",
            align: "center",
            span: 24,
            slot: true,
            viewDisplay: false,
            formslot: true,
            rules: [
              {
                required: true,
                message: "请选择附件",
                trigger: "blur"
              }
            ]
          }
        ]
      },
      // 管控措施
      controlMeasures: [],
      measureData: [],
      measureOption: {
        calcHeight: 30,
        tip: false,
        index: true,
        selection: false,
        addBtn: false,
        refreshBtn: false,
        columnBtn: false,
        indexWidth: 30,
        editBtn: false,
        delBtn: false,
        menuWidth: 100,
        column: [
          {
            label: "类型",
            prop: "gklx",
            align: "center",
            slot: true,
            width: 200
          },
          {
            label: "管控措施",
            prop: "gkcs",
            align: "center",
            slot: true
          }
        ]
      },
      // 弹窗：选择管控措施
      chooseMeasureDialog: false,
      filterYHJB: "",
      // 附件
      fjFileList: [],
      downloadHead: "/api/fileManager/download/",
      SetHeaders: { "Blade-Auth": getToken() },
      dialogType: "",
      viewLabel: "view",
      fxdjObj: {
        "1": "A",
        "2": "B",
        "3": "C",
        "4": "D"
      }
    };
  },
  computed: {
    ...mapGetters(["permission"]),

    // 应知卡按钮权限
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.knowablecard_add, false),
        viewBtn: this.vaildData(this.permission.knowablecard_view, false),
        delBtn: this.vaildData(this.permission.knowablecard_delete, false),
        editBtn: this.vaildData(this.permission.knowablecard_edit, false)
      };
    },

    // 应知卡列表勾选项ID
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  watch: {
    measureData() {
      if(this.measureData.length === 0) {
        this.form.fxgkcs = "";
      } else {
        this.form.fxgkcs = "fxgkcs";
      }
    }
  },
  mounted() {
    this.getMeasureTypes();
  },
  methods: {
    // 获取管控措施类型
    getMeasureTypes() {
      getControlMeasureTypes()
        .then(res => {
          this.controlMeasures = res.data.data;
        })
        .then(() => {
          this.onLoad(this.page);
        });
    },

    // 批量导出
    handleExport() {
      this.$confirm("是否批量导出应知卡?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let yzkbh =
          this.query.yzkbh === undefined || this.query.yzkbh === null
            ? ""
            : this.query.yzkbh;
        let gwmc =
          this.query.gwmc === undefined || this.query.gwmc === null
            ? ""
            : this.query.gwmc;
        let fxdj =
          this.query.fxdj === undefined || this.query.fxdj === null
            ? ""
            : this.query.fxdj;
        window.open(
          `/api/twoSinglesAndThreeCards/knowablecard/export?${
            this.website.tokenHeader
          }=${getToken()}&yzkbh=${yzkbh}&gwmc=${gwmc}&fxdj=${fxdj}`
        );
      });
    },

    // 新增
    rowSave(row, done, loading) {
      if (this.measureData.length === 0) {
        this.$message.warning("请添加或选择风险管控措施!");
        loading();
        return;
      }
      var isEmpty = false;
      this.measureData.forEach(item => {
        if (
          item.gklx === "" ||
          item.gklx === undefined ||
          item.gkcs === "" ||
          item.gkcs === undefined
        ) {
          isEmpty = true;
        }
      });
      if (isEmpty) {
        this.$message.warning("请填写正确的管控措施");
        loading();
        return;
      }
      for (let key in row) {
        if (key.indexOf("$") >= 0) {
          delete row[key];
        }
      }
      row["measuresList"] = [];
      this.measureData.forEach(item => {
        var measure = {
          gkcs: item.gkcs,
          gklx: item.gklx
        };
        if (item.id !== "" && item.id !== undefined) {
          measure["id"] = item.id;
        }
        row.measuresList.push(measure);
      });
      add(row).then(() => {
        this.onLoad(this.page);
        this.$message.success("操作成功!");
        done();
      });
    },

    // 编辑
    rowUpdate(row, index, done, loading) {
      if (this.measureData.length === 0) {
        this.$message.warning("请添加或选择风险管控措施!");
        loading();
        return;
      }
      var isEmpty = false;
      this.measureData.forEach(item => {
        if (
          item.gklx === "" ||
          item.gklx === undefined ||
          item.gkcs === "" ||
          item.gkcs === undefined
        ) {
          isEmpty = true;
        }
      });
      if (isEmpty) {
        this.$message.warning("请填写正确的管控措施");
        loading();
        return;
      }
      for (let key in row) {
        if (key.indexOf("$") >= 0) {
          delete row[key];
        }
      }
      row["measuresList"] = [];
      this.measureData.forEach(item => {
        var measure = {
          gkcs: item.gkcs,
          gklx: item.gklx
        };
        if (item.id !== "" && item.id !== undefined) {
          measure["id"] = item.id;
        }
        row.measuresList.push(measure);
      });
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message.success("操作成功!");
        done();
      });
    },

    // 删除一条
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message.success("操作成功!");
        });
    },

    // 删除多条
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message.success("操作成功!");
          this.$refs.crud.toggleSelection();
        });
    },

    // 打开查看、新增、编辑弹窗前
    beforeOpen(done, type) {
      this.measureData = [];
      this.fjFileList = [];
      this.dialogType = type;
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
          this.measureData = this.form.measuresList;
          if (this.form.bladeFile) {
            this.fjFileList.push({
              name: this.form.bladeFile.fileName,
              response: {
                code: 200,
                msg: "操作成功",
                success: true,
                data: this.form.bladeFile
              }
            });
          }
        });
      }
      done();
    },

    // 清空搜索条件
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },

    // 搜索条件改变事件
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },

    // 勾选
    selectionChange(list) {
      this.selectionList = list;
    },

    // 清空勾选
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },

    // 换页数
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page);
    },

    // 换每页显示数量
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad(this.page);
    },

    // 刷新
    refreshChange() {
      this.onLoad(this.page, this.query);
    },

    // 获取表格数据
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },

    /**
     * 上传附件
     */

    // 上传附件前
    beforeUploadFJ(file) {
      var isLimit = this.fjFileList.length + 1 <= 1;
      if (!isLimit) {
        this.$message.warning("只能选择一个附件!");
      }
      return isLimit;
    },

    // 上传附件成功
    uploadFJSuccess(response, file, fileList) {
      if (response.code !== 200 || response.success !== true) {
        return;
      }
      this.fjFileList = fileList;
      this.form.fj = this.formatFJ(this.fjFileList);
    },

    // 删除附件
    handleRemoveFJ(file, fileList) {
      this.fjFileList = fileList;
      this.form.fj = this.formatFJ(this.fjFileList);
    },

    // 格式化附件ID
    formatFJ(fileList) {
      var ids = [];
      fileList.forEach(item => {
        ids.push(item.response.data.id);
      });
      return ids.join(",");
    },

    /**
     * 管控措施
     */

    // 添加管控措施
    addControlMeasure() {
      this.measureData.push({
        gklx: "",
        gkcs: ""
      });
    },

    // 删除管控措施
    handleDeleteMeasure(row, index) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.measureData.splice(index, 1);
      });
    },

    /**
     * 弹窗：选择管控措施
     */

    // 打开选择管控措施弹窗
    handleSelectControlMeasure() {
      this.chooseMeasureDialog = true;
      this.filterYHJB = "";
    },

    // 选择管控措施
    chooseControlMeasure(list) {
      list.forEach(item => {
        this.measureData.push({
          gklx: "",
          gkcs: item.gkcs
        });
      });
      this.cancelChooseControlMeasure();
    },

    // 取消选择管控措施
    cancelChooseControlMeasure() {
      this.chooseMeasureDialog = false;
      this.filterYHJB = "";
    },

    // 关闭选择管控措施弹窗
    handleCloseChooseMeasure() {
      this.cancelChooseControlMeasure();
    }
  }
};
</script>

<style lang="scss" scpoed>
%fxdj_div {
  width: 27px;
  height: 27px;
  margin: 0 auto;
  color: #fff;
  font-weight: bold;
  padding-top: 2px;
}

%level_a_color {
  background-color: #ea4242;
}

%level_b_color {
  background-color: #fa9a3b;
}

%level_c_color {
  background-color: #fcd42a;
}

%level_d_color {
  background-color: #6db6eb;
}

.shouldknowcard {
  .fxdj_a {
    @extend %fxdj_div;
    @extend %level_a_color;
  }

  .fxdj_b {
    @extend %fxdj_div;
    @extend %level_b_color;
  }

  .fxdj_c {
    @extend %fxdj_div;
    @extend %level_c_color;
  }

  .fxdj_d {
    @extend %fxdj_div;
    @extend %level_d_color;
  }

  .avue-crud {
    .avue-crud__search {
      .avue-form__row:nth-child(1) {
        .el-form-item__label {
          text-align: unset;
          width: 90px !important;
        }

        .el-form-item__content {
          margin-left: 90px !important;
        }
      }
    }
  }

  .enclosure_div {
    a {
      font-size: 12px;
      color: #409eff;

      i {
        margin-right: 5px;
      }
    }
  }
}

.avue-dialog {
  .el-dialog {
    .avue-group {
      .avue-form__group {
        .el-form-item {
          .el-form-item__label {
            width: 110px !important;
          }

          .el-form-item__content {
            margin-left: 110px !important;
          }
        }

        .avue-form__row:nth-child(8) {
          .el-form-item {
            margin-bottom: 0px;
          }
        }
      }
    }
  }
}

.fxgkcsContent_div {
  .avue-crud {
    .el-table__empty-block,
    .el-table__header-wrapper,
    .avue-crud__menu,
    .avue-crud__pagination {
      display: none;
    }
  }
}

.choose_cm_footer {
  text-align: center;
  margin-top: 15px;

  .el-button {
    width: 100px;
    height: 35px;
  }
}
</style>